package com.wwh.memo.logic.dao

import android.content.ContentValues
import android.content.Context
import com.wwh.databasetest.MemoDatabaseHelper
import com.wwh.memo.logic.model.Memo

class MemoDAO (context : Context, version : Int){
    private val db = MemoDatabaseHelper(context, "MemoStore.db", version).writableDatabase

    fun addMemo(memo : Memo) {
        val values = ContentValues().apply {
            put("title", memo.title)
            put("content", memo.content)
            put("datetime", memo.datetime)
        }
        db.insert("memo", null, values)
    }

    fun updateMemo(memo : Memo) {
        val values = ContentValues()
        values.put("title", memo.title)
        values.put("content", memo.content)
        values.put("datetime", memo.datetime)
        db.update("memo", values, "id = ?", arrayOf(memo.id.toString()))
    }

    fun deleteMemo(memo : Memo) {
        db.delete("memo", "id = ?", arrayOf(memo.id.toString()))
    }

    fun queryMemos() : List<Memo>{
        val memoList = ArrayList<Memo>()
        val cursor = db.query("memo", null, null, null, null, null, null)
        if(cursor.moveToFirst()) {
            do{
                val titleIndex = cursor.getColumnIndex("title")
                val contentIndex = cursor.getColumnIndex("content")
                val idIndex = cursor.getColumnIndex("id")
                val datetimeIndex = cursor.getColumnIndex("datetime")

                if(titleIndex != -1 && contentIndex != -1 && idIndex != -1  && datetimeIndex != -1) {
                    var title = cursor.getString(titleIndex)
                    var content = cursor.getString(contentIndex)
                    val id = cursor.getInt(idIndex)
                    var datetime = cursor.getString(datetimeIndex)
                    if(content == null) content = ""
                    if(title == null) title = ""
                    if(datetime == null) datetime = ""

                    memoList.add(Memo(id, title, content, datetime))
                }

            } while (cursor.moveToNext())
        }
        cursor.close()
        return memoList
    }

    fun destroy() {
        db.close()
    }

}